import { defineStore } from "pinia";
import {routes, addRouteList, generateRouter } from '../routes/index'

export const useMenuList = defineStore("menuList", {
  state: () => {
    return {
      activeMenuList: [
        {
          path: '/home/index',
          name: 'index',
          fullPath: '/home/index',
          meta: {title: '首页',  hidden: true}
        },
      ],
      activeMenuPath: "/home/index",
      routes: routes,
      asyncRoutes: [], // 动态路由
      collapseStatus: true,
      getRouter: true
    };
  },
  getters: {
    menuList: (state) => {
      return state.activeMenuList;
    }
  },
  actions: {
    activeMenu(menu) {
      this.activeMenuPath = menu.path;
      if (!this.activeMenuList.some(s => s.path === menu.path)) {
        this.activeMenuList.push(menu);
      }
    },
    inActiveMenu(menu) {
      this.activeMenuList.forEach((item, index) => {  // 删除不是当前的menu
        if (item.path === menu.path && menu.path !== this.activeMenuPath) {
          this.activeMenuList = this.activeMenuList.filter(item => item.path !== menu.path)
        } else {
          this.activeMenuList = this.activeMenuList.filter(item => item.path !== menu.path)
          this.activeMenuPath = this.activeMenuList[this.activeMenuList.length - 1].path
        }
      });
    },
    currentActiveMenuPath(menu) {
        this.activeMenuPath = menu.fullPath
    },
    clearMenu() {
      this.activeMenuList = [
        {
          path: '/home/index',
          name: 'index',
          meta: {title: '首页',  hidden: true}
        },
      ]
    },
    // 更新菜单并追加路由（登录）
    async updateRouteList(ary) {

      let res = await generateRouter(ary)
      await addRouteList(res)

      this.routes = [ ...routes , ...res]
      console.log('123123', this.routes)

      return true
    },
    // 添加路由（浏览器刷新）
    async setAddRouter() {
      let find = JSON.parse(window.sessionStorage.getItem('q_async_routes'))
      if(!find) return

      let res = await generateRouter(find.asyncRoutes)
      await addRouteList(res)

      this.routes = [ ...routes , ...res]
    },
    changeRouteList(ary) {

    }
  },
  persist: {
    enabled: true, // 开启数据缓存
    strategies: [
      {
        key: 'q_async_routes',
        storage: sessionStorage,
        paths: ["asyncRoutes"],
      }
    ]
  }
});
